<template>
  <div>
    <el-form ref="editForm" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row>
        <el-col :span="24">
          <div class="form-info-title">
            <i class="el-icon-document" /><span>基本信息</span>
          </div>
        </el-col>
        <el-col :span="8">
          <el-form-item label="巡检厅局" required prop="institutionCode">
            <el-select v-model="formItem.institutionCode" placeholder="请选择巡检厅局" size="mini">
              <el-option v-for="(item) in institutions" :key="item.code" :label="item.name " :value="item.code" @click.native="changeName(item)" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="开始时间" required prop="startDateTime">
            <el-date-picker
              v-model="formItem.startDateTime"
              type="date"
              placeholder="选择日期时间"
              align="right"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结束时间" required prop="endDateTime">
            <el-date-picker
              v-model="formItem.endDateTime"
              type="date"
              placeholder="选择日期时间"
              align="right"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="时长（时）" required prop="duration">
            <el-input-number v-model="formItem.duration" :precision="2" :step="1" :max="1000000000" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="计划状态">
            <el-radio-group v-model="formItem.disabled">
              <el-radio :label="false">启用</el-radio>
              <el-radio :label="true">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <div class="form-info-title">
            <i class="el-icon-document" /><span>巡检内容</span>
          </div>
        </el-col>
        <el-col :span="24">
          <PageableTable ref="table" :loading="false" :table-height="800" :data="tableData" :span-method="objectSpanMethod" :disable-pageable="true" @selection-change="tableSelection">
            <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
              <template slot-scope="scope">
                <column-render :render="column.render" :row="scope.row" :column="column" />
              </template>
            </el-table-column>
            <el-table-column type="selection" :label="'选择'" />
          </PageableTable>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import PageableTable from '@neu/biz-core/components/PageableTable'
import { create, update, detail } from '@neu/dcom-ui/api/hnInspectionPlanHealth'
import { clone } from '@neu/biz-core/utils/utils'
import { findByDictionaryType } from '@neu/dcom-ui/api/dictionary'
import { list as itemList } from '@neu/dcom-ui/api/hnInspectionItem'
import { formatDate } from '@neu/biz-core/utils/utils'
// 定义一个表单原始项
const formItem = {
  // 厅局
  institutionCode: '',
  institutionName: '',
  startDateTime: '',
  endDateTime: '',
  duration: 1,
  disabled: true,
  items: []
}
export default {
  name: 'HnInspectionPlanEdit',
  components: {
    PageableTable
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      tableData: [],
      institutions: [],
      editorOption: {},
      types: [],
      categories: [{ name: '日巡检', code: 'day' }, { name: '定期健康巡检', code: 'regular' }, { name: '重保服务', code: 'service' }],
      // 编辑的表单内容
      formItem: clone(formItem),
      // 表单验证规则
      rules: {
        institutionCode: [{ required: true, message: '不能为空', trigger: 'change' }],
        startDateTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
        endDateTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
        duration: [{ required: true, message: '持续时间不能为空', trigger: 'change' }],
        item: [{ required: true, message: '不能为空', trigger: 'blur' }],
        dataType: [{ required: true, message: '不能为空', trigger: 'change' }],
        rule: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      insideColumns: [
        { title: '类别', key: 'itemType', display: true, render: (h, params) => {
          const status = this.types.filter(t => {
            return t.code === params.row.itemType
          })
          const statusDesc = status.length === 1 ? status[0].text : params.row.statusDesc
          return h('span', statusDesc)
        } },
        { title: '内容', key: 'item', display: true },
        { title: '结果值', key: 'candidateValueArr', display: true,
          render: (h, params) => {
            const desc = params.row.candidateValueArr
            let display = ''
            if (Array.isArray(desc) && desc.length > 0) {
              desc.forEach(element => {
                display += element + '/'
              })
              display = display.substring(0, display.length - 1)
            }
            return h('span', display)
          }
        },
        { title: '异常判断规则', key: 'rule', display: true }
      ],
      itemTypeArr: [],
      itemTypePos: 0
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler() {
        if (this.id) {
          this.fetch()
        }
      },
      immediate: true
    }
  },
  created() {
    findByDictionaryType('hnInspectionItemType').then(res => {
      if (res.status === 'success') {
        this.types = res.data
      }
    })
    this.institutions = this.$store.getters['dcom/projectUserInfo'].institutions
    const obj = {
      's_disabled': 'false',
      's_category': 'regular'
    }
    itemList(obj).then(res => {
      if (res.status === 'success') {
        const data = res.data
        this.tableData = data.sort((v1, v2) => {
          const x = v1.itemType.toLowerCase()
          const y = v2.itemType.toLowerCase()
          if (x < y) { return -1 }
          if (x > y) { return 1 }
          return 0
        })
        this.dataData = this.tableData.sort((v1, v2) => {
          if (v1.itemType === v2.itemType) {
            return v1.sort - v2.sort
          }
          return 0
        })
        this.merge()
        if (this.formItem.items) {
          setTimeout(() => {
            this.toggleSelection(this.formItem.items) // 需要默认勾选的数据
          }, 100)
        } else {
          if (this.id) {
            detail(this.id).then(response => {
              this.formItem = {
                ...response.data
              }
              setTimeout(() => {
                this.toggleSelection(this.formItem.items) // 需要默认勾选的数据
              }, 100)
            })
          }
        }
      }
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem = clone(formItem)
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            if (formatDate(this.formItem.startDateTime) > formatDate(this.formItem.endDateTime)) {
              return this.$message({
                showClose: true,
                message: '巡检开始时间不能大于巡检结束时间',
                type: 'error'
              })
            }
            if (this.formItem.items.length === 0) {
              return this.$message({
                showClose: true,
                message: '巡检内容不能为空',
                type: 'error'
              })
            }
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.editForm.resetFields()
      this.formItem = clone(this.formItem)
    },
    /** 删除某一项 */
    removeUser(tag) {
      this.formItem.candidateValueArr = this.formItem.candidateValueArr.filter(t => {
        return t !== tag
      })
    },
    /** 删除所有项 */
    clearCandidate() {
      this.formItem.candidateValueArr = []
    },
    add(value) {
      if (!this.formItem.candidateValueArr.includes(value)) {
        this.formItem.candidateValueArr.push(value)
        this.test = ''
      }
    },
    merageInit() {
      this.itemTypeArr = []
      this.itemTypePos = 0
    },
    merge() {
      this.merageInit()
      for (let i = 0; i < this.tableData.length; i++) {
        if (i === 0) {
          // 第一行必须存在
          this.itemTypeArr.push(1)
          this.itemTypePos = 0
        } else {
          // 判断当前元素与上一个元素是否相同,eg：this.itemTypePos 是 this.itemTypeArr
          // 第一列
          if (this.tableData[i].itemType === this.tableData[i - 1].itemType) {
            this.itemTypeArr[this.itemTypePos] += 1
            this.itemTypeArr.push(0)
          } else {
            this.itemTypeArr.push(1)
            this.itemTypePos = i
          }
        }
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
      // 第一列的合并方法
        const row1 = this.itemTypeArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0 // 如果被合并了row = 0; 则他这个列需要取消
        return {
          rowspan: row1,
          colspan: col1
        }
      }
    },
    tableSelection(sel) {
      this.formItem.items = sel
    },
    changeName(item) {
      this.formItem.institutionName = item.name
    },
    toggleSelection(data) {
      const selectIds = this.formItem.items.map(t => t.id)
      const rows = this.tableData.filter(t => {
        return selectIds.includes(t.id)
      })
      if (rows) {
        for (const row of rows) {
          this.$nextTick(function() {
            this.$refs.table.$refs.pageableTable.toggleRowSelection(row)
          })
        }
      } else {
        this.$refs.table.$refs.pageableTable.clearSelection()
      }
    }
  }
}
</script>

